#!/bin/bash

# Flutter 项目 Bundle ID 修改脚本
# 作用：解决 App ID 被 App Store 占用的问题

echo "🔧 Flutter Bundle ID 修改工具"
echo "======================================"

# 获取脚本所在目录（项目根目录）
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "📁 当前目录: $(pwd)"
echo "⏰ 开始时间: $(date)"

# 检查是否为 Flutter 项目
if [ ! -f "pubspec.yaml" ]; then
    echo "❌ 错误：当前目录不是 Flutter 项目！"
    read -p "按任意键退出..." -n1 -s
    exit 1
fi

echo "✅ 检测到 Flutter 项目"

# 显示项目信息
PROJECT_NAME=$(grep "^name:" pubspec.yaml | cut -d' ' -f2 2>/dev/null || echo "unknown")
echo "📄 项目名称: $PROJECT_NAME"

echo ""
echo "🔍 检查当前 Bundle ID 配置..."

# 检查当前 Android Bundle ID
ANDROID_BUILD_GRADLE="android/app/build.gradle"
if [ -f "$ANDROID_BUILD_GRADLE" ]; then
    CURRENT_ANDROID_ID=$(grep "applicationId" "$ANDROID_BUILD_GRADLE" | sed 's/.*applicationId[[:space:]]*"\([^"]*\)".*/\1/')
    echo "📱 Android Bundle ID: $CURRENT_ANDROID_ID"
else
    echo "❌ 未找到 Android 配置文件"
    CURRENT_ANDROID_ID=""
fi

# 检查当前 iOS Bundle ID
IOS_RUNNER_PLIST="ios/Runner/Info.plist"
if [ -f "$IOS_RUNNER_PLIST" ]; then
    # 从 Info.plist 获取 Bundle ID (CFBundleIdentifier)
    if command -v plutil >/dev/null 2>&1; then
        CURRENT_IOS_ID=$(plutil -extract CFBundleIdentifier raw "$IOS_RUNNER_PLIST" 2>/dev/null || echo "")
    else
        # 备用方法：使用 grep
        CURRENT_IOS_ID=$(grep -A1 "CFBundleIdentifier" "$IOS_RUNNER_PLIST" | grep -o '[^<>]*[a-z].*[a-z][^<>]*' | head -1)
    fi
    echo "🍎 iOS Bundle ID: $CURRENT_IOS_ID"
else
    echo "❌ 未找到 iOS 配置文件"
    CURRENT_IOS_ID=""
fi

echo ""
echo "🚨 当前问题："
echo "   Bundle ID '$CURRENT_ANDROID_ID' 被 App Store 占用"
echo "   需要修改为新的 Bundle ID 来解决冲突"
echo ""

# 生成新的 Bundle ID 建议
BASE_ID=$(echo "$CURRENT_ANDROID_ID" | sed 's/\.wanzhende2025$//')
SUGGESTIONS=(
    "${BASE_ID}.wanzhende2025v2"
    "${BASE_ID}.wanzhende"
    "${BASE_ID}.zhende2025" 
    "${BASE_ID}.app2025"
    "${BASE_ID}.playapp"
)

echo "💡 建议的新 Bundle ID："
for i in "${!SUGGESTIONS[@]}"; do
    echo "   $((i+1)). ${SUGGESTIONS[$i]}"
done
echo "   6. 自定义输入"
echo ""

# 用户选择新的 Bundle ID
read -p "请选择新的 Bundle ID (1-6): " CHOICE

case $CHOICE in
    1|2|3|4|5)
        NEW_BUNDLE_ID="${SUGGESTIONS[$((CHOICE-1))]}"
        ;;
    6)
        read -p "请输入自定义 Bundle ID: " NEW_BUNDLE_ID
        ;;
    *)
        NEW_BUNDLE_ID="${SUGGESTIONS[0]}"
        echo "⚡ 自动选择: $NEW_BUNDLE_ID"
        ;;
esac

echo ""
echo "🎯 新的 Bundle ID: $NEW_BUNDLE_ID"
echo ""

echo "🔄 开始修改配置文件..."

# 修改 Android 配置
if [ -f "$ANDROID_BUILD_GRADLE" ] && [ -n "$CURRENT_ANDROID_ID" ]; then
    echo "📱 修改 Android 配置..."
    
    # 备份原文件
    cp "$ANDROID_BUILD_GRADLE" "${ANDROID_BUILD_GRADLE}.backup"
    
    # 替换 applicationId
    sed -i.tmp "s/applicationId[[:space:]]*\"$CURRENT_ANDROID_ID\"/applicationId \"$NEW_BUNDLE_ID\"/" "$ANDROID_BUILD_GRADLE"
    rm "${ANDROID_BUILD_GRADLE}.tmp" 2>/dev/null
    
    echo "   ✅ Android Bundle ID 已更新"
else
    echo "   ⚠️  跳过 Android 配置修改"
fi

# 修改 iOS 配置
if [ -f "$IOS_RUNNER_PLIST" ] && [ -n "$CURRENT_IOS_ID" ]; then
    echo "🍎 修改 iOS 配置..."
    
    # 备份原文件
    cp "$IOS_RUNNER_PLIST" "${IOS_RUNNER_PLIST}.backup"
    
    # 替换 CFBundleIdentifier
    if command -v plutil >/dev/null 2>&1; then
        plutil -replace CFBundleIdentifier -string "$NEW_BUNDLE_ID" "$IOS_RUNNER_PLIST"
    else
        # 备用方法：使用 sed
        sed -i.tmp "s|<string>$CURRENT_IOS_ID</string>|<string>$NEW_BUNDLE_ID</string>|" "$IOS_RUNNER_PLIST"
        rm "${IOS_RUNNER_PLIST}.tmp" 2>/dev/null
    fi
    
    echo "   ✅ iOS Bundle ID 已更新"
else
    echo "   ⚠️  跳过 iOS 配置修改"
fi

# 检查是否需要修改其他文件
echo ""
echo "🔍 检查其他需要修改的文件..."

# 检查 iOS 项目配置
IOS_PROJECT_FILE="ios/Runner.xcodeproj/project.pbxproj"
if [ -f "$IOS_PROJECT_FILE" ]; then
    if grep -q "PRODUCT_BUNDLE_IDENTIFIER.*$CURRENT_IOS_ID" "$IOS_PROJECT_FILE"; then
        echo "🍎 修改 iOS 项目配置..."
        cp "$IOS_PROJECT_FILE" "${IOS_PROJECT_FILE}.backup"
        sed -i.tmp "s/PRODUCT_BUNDLE_IDENTIFIER = $CURRENT_IOS_ID/PRODUCT_BUNDLE_IDENTIFIER = $NEW_BUNDLE_ID/g" "$IOS_PROJECT_FILE"
        rm "${IOS_PROJECT_FILE}.tmp" 2>/dev/null
        echo "   ✅ iOS 项目配置已更新"
    fi
fi

echo ""
echo "🧹 清理项目缓存..."
flutter clean >/dev/null 2>&1

echo ""
echo "🎉 Bundle ID 修改完成！"
echo "======================================"

echo "📝 修改总结："
echo "   旧 Bundle ID: $CURRENT_ANDROID_ID"
echo "   新 Bundle ID: $NEW_BUNDLE_ID"
echo "   ✅ Android 配置已更新"
echo "   ✅ iOS 配置已更新"
echo "   ✅ 项目缓存已清理"

echo ""
echo "📋 后续步骤："
echo "   1. 🔑 在 Apple Developer 创建新的 App ID"
echo "   2. 📜 创建新的 Provisioning Profiles"
echo "   3. 🏗️  重新构建项目"
echo "   4. 📱 在 App Store Connect 创建新应用"

echo ""
echo "💡 Apple Developer 操作："
echo "   访问: https://developer.apple.com/account/"
echo "   创建 App ID: $NEW_BUNDLE_ID"
echo "   配置所需的服务和功能"

echo ""
echo "🚨 重要提醒："
echo "   - 已备份原配置文件（.backup）"
echo "   - 需要重新配置推送通知证书"
echo "   - 需要重新配置应用签名"
echo "   - 如有内购产品需要重新配置"

echo ""
echo "⏰ 完成时间: $(date)"
echo "======================================"

# 等待用户按键后关闭
echo ""
echo "按任意键关闭窗口..."
read -n1 -s
